package com.tourism.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tourism.domain.entity.Favorite;
import com.tourism.service.FavoriteService;
import com.tourism.core.common.utils.Result;
import com.tourism.core.security.util.SecurityHolderUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;


@RequestMapping("/api/admin/favorite")
@RestController
public class FavoriteController {

    @Autowired
    private FavoriteService favoriteService;

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('favorite:list')")
    public Result<?> list() {
        return Result.success(favoriteService.getAllFavoritesByUserId());
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('favorite:save')")
    public Result<Boolean> save(@RequestBody Favorite favorite) {
        favorite.setUserId(SecurityHolderUtils.getUserId());
        return favoriteService.save(favorite) ? Result.success() : Result.failure();
    }


    @GetMapping("/cancel/{attractionId}")
    @PreAuthorize("hasAuthority('favorite:cancel')")
    public Result<Boolean> cancel(@PathVariable("attractionId") Long attractionId) {
        LambdaQueryWrapper<Favorite> lqw = new LambdaQueryWrapper<Favorite>().eq(Favorite::getAttractionId, attractionId);
        return favoriteService.remove(lqw) ? Result.success() : Result.failure();
    }

    @GetMapping("/isFavorite/{id}")
    @PreAuthorize("hasAuthority('favorite:isFavorite')")
    public Result<Boolean> isFavorite(@PathVariable Long id) {
        return favoriteService.lambdaQuery().eq(Favorite::getAttractionId, id).eq(Favorite::getUserId, SecurityHolderUtils.getUserId()).exists() ? Result.success(true) : Result.success(false);
    }
}
